package com.atguigu.gmall.controller;

import com.atguigu.gmall.client.service.OrderFeignClientService;
import com.atguigu.gmall.client.service.UserFeignClientService;
import com.atguigu.gmall.entity.*;
import com.atguigu.gmall.result.RetVal;
import com.atguigu.gmall.result.RetValCodeEnum;
import com.atguigu.gmall.service.SeckillService;
import com.atguigu.gmall.util.AuthContextHolder;
import com.atguigu.gmall.util.DateUtil;
import com.atguigu.gmall.util.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/seckill")
public class SeckillController {

    @Autowired
    private SeckillService seckillService;
    @Autowired
    private UserFeignClientService userFeignClientService;
    @Autowired
    private OrderFeignClientService orderFeignClientService;

    @GetMapping("/queryAllSeckillProduct")
    public RetVal queryAllSeckillProduct() {
        List<SeckillProduct> seckillProducts = seckillService.findSeckillProduct();
        return RetVal.ok(seckillProducts);
    }
    //2.根据skuId 获取秒杀对象数据
    @GetMapping("/getSeckillProductBySkuId/{skuId}")
    public RetVal getSeckillProductBySkuId(@PathVariable Long skuId) {
        SeckillProduct seckillProduct = seckillService.getSeckillProductBySkuId(skuId);
        return RetVal.ok(seckillProduct);
    }
    //3.生成秒杀参数
    @GetMapping("/generateSeckillCode/{skuId}")
    public RetVal generateSeckillCode(HttpServletRequest request, @PathVariable Long skuId){
        String userId = AuthContextHolder.getUserId(request);//获取用户id
        SeckillProduct seckillProduct = seckillService.getSeckillProductBySkuId(skuId); //查询秒杀商品
        Date currentTime = new Date();
        //当前时间如果在秒杀时间范围内 则生成下单码
        if (DateUtil.dateCompare(seckillProduct.getStartTime(),currentTime) && DateUtil.dateCompare(currentTime,seckillProduct.getEndTime())){
            //生成规则 将用户Id使用md5加密
            String seckillCode = MD5.encrypt(userId);
            return RetVal.ok(seckillCode);
        }
        return RetVal.fail().message("不在秒杀时间之内"); //不在秒杀时间之内
    }

    @PostMapping("/prepareSeckill/{skuId}")
    public RetVal prepareSeckill(@PathVariable Long skuId,@RequestParam String seckillCode,HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        if(!MD5.encrypt(userId).equals(seckillCode)){
            return RetVal.build(null, RetValCodeEnum.SECKILL_ILLEGAL);//当预下单的时候用户不匹配 报异常
        }
        //判断当前商品的状态位是否正常
        boolean flag = seckillService.checkSeckillProductStatusBySkuId(skuId);
        if (flag){ //状态正常
            seckillService.sendRabbitMqMessage(userId,skuId); //发送消息队列预处理此项订单
        }else {
            return RetVal.build(null, RetValCodeEnum.SECKILL_FINISH); //秒杀商品已经卖完
        }
        return RetVal.ok();
    }

    //查询订单
    @GetMapping("/hasQualified/{skuId}")
    public RetVal hasQualified(@PathVariable Long skuId,HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        return seckillService.hasQualified(skuId,userId);
    }
    //6.秒杀商品确认信息
    @GetMapping("/seckillConfirm")
    public RetVal seckillConfirm(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);//获取用户的id
        //查询商品的订单明细
        PrepareSeckillOrder prepareSeckillOrder = seckillService.getseckillPrepareOrderInfoByUserId(userId);
        if (prepareSeckillOrder == null)
            return RetVal.fail().message("非法请求");
        //获取用户的收获地址
        List<UserAddress> userAddresses = userFeignClientService.getUserAddressByUserId(userId);
        Map<String, Object> retMap = this.packageResultMap(prepareSeckillOrder,userAddresses);
        return RetVal.ok(retMap);
    }

    //7.提交订单
    @PostMapping("/submitSecKillOrder")
    public RetVal submitSecKillOrder(@RequestBody OrderInfo orderInfo , HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        //检查用户是否有预订单
        PrepareSeckillOrder prepareSeckillOrder = seckillService.getseckillPrepareOrderInfoByUserId(userId);
        if (prepareSeckillOrder == null)
            return RetVal.fail();//没有预订单，非法提交订单
        //获取订单详情，远程调用orderinfo,保存订单
        //检测无刷新重复提交
        Long orderId = orderFeignClientService.saveOrderInfoAndDetail(orderInfo);
        if (orderId == null)
            return RetVal.fail();
        //删除预订单信息 + 将订单保存到缓存
        seckillService.deletePrepareSeckillOrder(userId,orderId);
        return RetVal.ok(orderId);
    }

    private Map<String, Object> packageResultMap( PrepareSeckillOrder prepareSeckillOrder, List<UserAddress> userAddresses) {
        SeckillProduct seckillProduct = prepareSeckillOrder.getSeckillProduct();
        //d.秒杀商品的订单明细
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setSkuId(seckillProduct.getSkuId());
        orderDetail.setSkuName(seckillProduct.getSkuName());
        orderDetail.setImgUrl(seckillProduct.getSkuDefaultImg());
        orderDetail.setSkuNum(prepareSeckillOrder.getBuyNum()+"");
        orderDetail.setOrderPrice(seckillProduct.getCostPrice());
        List<OrderDetail> orderDetailList = new ArrayList<>();
        orderDetailList.add(orderDetail);
        //e.返回数据给页面
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("userAddressList",userAddresses);
        retMap.put("orderDetailList",orderDetailList);
        retMap.put("totalMoney",seckillProduct.getCostPrice());
        return retMap;
    }


}
